/*
 * igo: com.cctv.igo.security.service.AuthenticationService.java Create On 2011-5-27 下午07:33:13 By Q-Wang
 * $Revision: 1.1 $
 */
package com.ctvit.framework.security.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;

import com.ctvit.framework.web.context.ContextHolder;


/**
 * @author <a href="mailto:apeidou@gmail.com">Q-Wang</a>
 *
 */
public class AuthenticationService {

	protected Logger logger = LoggerFactory.getLogger(getClass());

	//	private AuthenticationManager authenticationManager;
	//
	//	/**
	//	 * @param authenticationManager the authenticationManager to set
	//	 */
	//	public void setAuthenticationManager(AuthenticationManager authenticationManager) {
	//		this.authenticationManager = authenticationManager;
	//	}

	public AuthenticationManager getAuthenticationManager() {
		return (AuthenticationManager)ContextHolder.getBean(AuthenticationManager.class);
	}


	public boolean login(String username, String password) {
		UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
		try {
			Authentication authentication = getAuthenticationManager().authenticate(token);
			if (authentication!=null&&authentication.isAuthenticated()) {
				SecurityContextHolder.getContext().setAuthentication(authentication);
				return true;
			}
			return false;
		} catch (AuthenticationException e) {
			logger.error("Authenticate Failure:" + username, e);
			return false;
		}
	}
}
